<template>
  <div class="login-page">
    <el-card class="login-card">
      <!-- 卡片头部：包含标题和管理员入口 -->
      <div class="card-header">
        <div class="manager-login" @click="goToManagerLogin">
          <el-icon>
            <Setting />
          </el-icon>
          <span>管理员登录</span>
        </div>
        <h2 class="title">聘途</h2>
      </div>
      <!-- 用户类型选择（默认求职端） -->
      <div class="user-type">
        <el-button
          type="primary"
          :class="{ active: userType === 'recruiter' }"
          @click="toggleUserType('recruiter')"
          plain
          class="recruiter-btn"
        >
          我要招聘
        </el-button>
        <el-button
          type="primary"
          :class="{ active: userType === 'seeker' }"
          @click="toggleUserType('seeker')"
          plain
          class="seeker-btn"
        >
          我要求职
        </el-button>
      </div>

      <!-- 登录表单 -->
      <el-form :model="form" :rules="rules" ref="loginForm" label-width="0">
        <el-form-item prop="phone">
          <el-input
            v-model="form.phone"
            prefix-icon=" el-icon-phone"
            type="tel"
            placeholder="请输入手机号"
            pattern="[0-9]{11}"
            :maxlength="11"
          >
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            prefix-icon=" el-icon-lock"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            show-password
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="isLoading"
            style="width: 100%"
          >
            立即登录
          </el-button>
        </el-form-item>
        <!-- 注册链接 -->
        <div class="link-group">
          <!-- 登录页面中的注册链接 -->
          <el-button @click="goToRegister" class="register"
            >还没有账号？立即注册</el-button
          >
          <div class="forgetpassword">
            <el-button @click="goToForgetPassword" class="register"
              >忘记密码</el-button
            >
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {
  getSeekerBasicInfo,
  loginByRecruiter,
  loginBySeeker,
  getRectuiterBasicInfo,
} from "@/api/login";
import { Message } from "element-ui";
import { mapState, mapActions } from "vuex";
import { initWs } from "@/services/websocket";

export default {
  data() {
    return {
      userType: "seeker",
      timer: null,
      form: {
        phone: "",
        password: "",
      },
      isLoading: false,
      isSending: false,
      rules: {
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入有效手机号",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "submit" },
          {
            min: 4,
            max: 20,
            message: "密码长度在4-20位之间",
            trigger: "submit",
          },
        ],
      },
    };
  },

  computed: {
    ...mapState("recruiter", {
      recruiterUserInfo: "userInfo",
    }),
    ...mapState("seeker", {
      seekerUserInfo: "userInfo",
    }),
    ...mapState("recruiter", {
      registerStatus: "registerStatus",
    }),
    isValidPhone() {
      return /^1[3-9]\d{9}$/.test(this.form.phone);
    },
  },

  created() {
    if (this.$route.query.userType) {
      this.userType = this.$route.query.userType;
    }
    // 从路由参数中获取 userType
    if (this.$route.query.userType === "recruiter") {
      this.userType = "recruiter"; // 设置为招聘端
    }
    this.checkAndRedirect();
  },

  methods: {
    ...mapActions(["login", "setTempToken", "clearAuth"]),
    ...mapActions("chat", ["initChatModule"]),
    toggleUserType(type) {
      this.userType = type;
    },
    // 跳转到管理员登录页
    goToManagerLogin() {
      this.$router.push("/manage-login");
    },

    //跳转到注册页面
    goToRegister() {
      this.$router.push({
        path: "/registerbyperson",
        query: { userType: this.userType },
      });
    },
    //跳转到修改密码页面
    goToForgetPassword() {
      this.$router.push({
        path: "/forgetpassword",
        query: { userType: this.userType },
      });
    },
    //登录
    async handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (!valid) return;

        try {
          this.isLoading = true;
          const { phone, password } = this.form;
          const loginResponse = await (this.userType === "recruiter"
            ? loginByRecruiter({ phone, password })
            : loginBySeeker({ phone, password }));

          // 获取业务状态码
          const { code: businessCode } = loginResponse.data;

          if (businessCode === 201) {
            if (this.userType === "recruiter") {
              const { status, token } = loginResponse.data.data;
              if (status) {
                // 已注册
                this.$store.commit("recruiter/SET_TOKEN", token);
                const isInfoLoaded = await this.$store.dispatch(
                  "recruiter/fetchRectuiterInfo"
                );
                //console.log(this.$store.state.recruiter.userInfo);
                if (isInfoLoaded) {
                  this.$router.replace("/company");
                  initWs(token, this.userType);
                  this.$store.dispatch("chat/initChatModule", {
                    userType: this.userType,
                  });
                } else {
                  Message.error("登录异常，请稍后尝试");
                }
              } else {
                // 未注册
                this.$store.commit("recruiter/SET_TEMP_TOKEN", token);
                initWs(token, this.userType);
                this.$store.dispatch("chat/initChatModule", {
                  userType: this.userType,
                });
                this.$router.replace("/companyregister");
              }
            } else {
              // 求职者登录处理
              // 成功返回Token
              const token = loginResponse.data.data;
              this.$store.commit("seeker/SET_TOKEN", token);
              await this.$store.dispatch("seeker/fetchSeekerInfo");
              await this.$store.dispatch("seeker/fetchProjectExperience");
              await this.$store.dispatch("seeker/fetchWorkExperience");

              // 确保用户信息已更新到Vuex
              //console.log("求职者用户信息:", this.$store.state.seeker.userInfo);

              initWs(token, this.userType);
              this.$store.dispatch("chat/initChatModule", {
                userType: this.userType,
              });

              this.$router.replace("/seekerHomePage");
            }
          } else {
            throw new Error(loginResponse.message || "登录失败");
          }
        } catch (error) {
          if (error.response) {
            const { status, data } = error.response;
            if (status === 404) {
              Message.error("该账号还没注册，请先注册");
            } else {
              // 其他状态码的错误处理
              Message.error(data.msg || `网络错误: ${status}`);
            }
          } else {
            // 处理网络连接问题（如超时、断网）
            Message.error("网络请求失败，请检查网络连接");
          }
        } finally {
          this.isLoading = false;
        }
      });
    },

    // 检查并跳转
    async checkAndRedirect() {
      // 初始化两个用户类型的登录状态
      let isRecruiterLoggedIn = false;
      let isSeekerLoggedIn = false;

      try {
        const [recruiterResult, seekerResult] = await Promise.allSettled([
          getRectuiterBasicInfo().catch((err) => ({ error: err })),
          getSeekerBasicInfo().catch((err) => ({ error: err })),
        ]);
        // 1. 处理招聘者信息请求结果
        if (recruiterResult.status === "fulfilled") {
          const res = recruiterResult.value;
          if (res.data?.code === 201) {
            isRecruiterLoggedIn = true;
          } else {
            this.$store.commit("recruiter/CLEAR_STATE");
            console.log("招聘者未登录或信息无效");
          }
        } else {
          this.$store.commit("recruiter/CLEAR_STATE");
          console.error("获取招聘者信息请求失败：", recruiterResult.reason);
        }

        if (seekerResult.status === "fulfilled") {
          const res = seekerResult.value;
          if (res.data?.code === 201) {
            isSeekerLoggedIn = true;
          } else {
            this.$store.commit("seeker/CLEAR_STATE");
            console.log("求职者未登录或信息无效");
          }
        } else {
          this.$store.commit("seeker/CLEAR_STATE");
          console.error("获取求职者信息请求失败：", seekerResult.reason);
        }
        if (isRecruiterLoggedIn && !isSeekerLoggedIn) {
          this.$router.push("/company");
        } else if (!isRecruiterLoggedIn && isSeekerLoggedIn) {
          this.$router.push("/seekerHomePage");
        } else if (isRecruiterLoggedIn && isSeekerLoggedIn) {
          if (this.userType === "seeker") {
            this.$router.push("/seekerHomePage");
          } else {
            this.$router.push("/company");
          }
        }
      } catch (error) {
        console.error("checkAndRedirect 全局错误：", error);
      }
    },
  },
};
</script>

<style scoped>
@import "element-ui/lib/theme-chalk/index.css";

.card-header {
  position: relative;
  margin-bottom: 30px;
  text-align: center;
}

.manager-login {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  color: #909399;
  cursor: pointer;
  font-size: 14px;
}

.manager-login:hover {
  color: #409eff;
}

.manager-login .el-icon {
  margin-right: 4px;
}

.title {
  margin: 0;
  padding: 5px 0;
  font-size: 24px;
  color: #409eff;
}

.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  /* 背景图片路径（根据实际存放位置调整） */
  background-image: url(../../../public/image/登录页面背景.png);
  /* 推荐使用public目录绝对路径 */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #f0f2f5;
  /* 备用背景色 */
}

.login-card {
  padding: 30px 40px;
  width: 400px;
  background-color: rgba(255, 255, 255, 0.3);
  /* 提高背景透明度 */
}

.user-type {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  gap: 15px;
}

/* 用户类型按钮样式 */
.user-type .el-button {
  flex: 1;
  padding: 12px 0;
  font-size: 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
  min-width: 140px;
  border: 1px solid #e4e7ed;
}

.user-type .el-button.active {
  background-color: #409eff;
  color: white;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  border-color: #409eff;
  /* 激活时边框颜色 */
}

.captcha-container {
  display: flex;
  gap: 10px;
}

.link-group {
  position: relative;
  margin-top: 25px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.el-input__inner {
  height: 48px;
  font-size: 16px;
}

.el-button--primary {
  height: 50px;
  font-size: 16px;
  border-radius: 8px;
}

.forgetpassword {
  position: absolute;
  top: 30px;
  right: 0px;
}

.register,
.forgetpassword {
  border: none;
  background-color: transparent;
}

.register:hover,
.register:active,
.forgetpassword:hover,
.forgetpassword:active {
  background-color: transparent !important;
}

.manager-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
  cursor: pointer;
}
</style>